package com.beiwei.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.beiwei.auto.mode.Company;
import com.beiwei.auto.mode.Permission;
import com.beiwei.auto.mode.User;
import com.beiwei.mode.VUser;
import com.beiwei.service.CompanyService;
import com.beiwei.service.UserService;

public class CustomRealm extends AuthorizingRealm {

	// 注入service
	@Autowired
	private UserService userService;
	@Autowired
	private CompanyService companyService;

	// 设置realm的名称
	@Override
	public void setName(String name) {
		super.setName("customRealm");
	}
	
	// 支持什么类型的token
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof UsernamePasswordToken;
	}

	// realm的认证方法，从数据库查询用户信息
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		// token是用户输入的用户名和密码
		// 第一步从token中取出用户名
		String usercode = (String) token.getPrincipal();

		// 第二步：根据用户输入的userCode从数据库查询
		User user = null;
		try {
			user = userService.findUserByUsercode(usercode);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		// 如果查询不到返回null
		if (user == null) {//
			return null;
		}
		// 从数据库查询到密码
		String password = user.getPassword();

		// 盐
		String salt = user.getSalt();

		VUser vUser = new VUser();
		vUser.setUserId(user.getUserId());
		vUser.setUsercode(user.getUsercode());
		vUser.setUsername(user.getUsername());
		vUser.setUserJobId(user.getUserJobId());
		vUser.setUserCompanyId(user.getUserCompanyId());
		vUser.setUserRoleIds(user.getUserRoleIds());
		vUser.setLocked(user.getLocked());
		vUser.setDelFlag(user.getDelFlag());
		vUser.setLeadId(user.getLeadId());
		vUser.setSalt(user.getSalt());
		vUser.setPassword(user.getPassword());
		// 根据用户id取出菜单
		List<Permission> menus = null;
		Company userCompany = null;
		try {
			// 通过service取出菜单
			menus = userService.findMenuListByUserRoleIds(vUser.getUserRoleIds());
			userCompany = companyService.findCompanyByCompanyId(vUser.getUserCompanyId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 将用户菜单 设置到vUser
		vUser.setMenus(menus);
		vUser.setUserCompany(userCompany);

		// /将activeUser设置simpleAuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(vUser, password,
				ByteSource.Util.bytes(salt), this.getName());

		return simpleAuthenticationInfo;
	}

	// 用于授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		// 从 principals获取主身份信息
		// 将getPrimaryPrincipal方法返回值转为真实身份类型（在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型），
		VUser vUser = (VUser) principals.getPrimaryPrincipal();

		// 根据身份信息获取权限信息
		// 从数据库获取到权限数据
		List<Permission> permissionList = null;
		try {
			permissionList = userService.findPermissionListByUserRoleIds(vUser.getUserRoleIds());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 单独定一个集合对象
		List<String> permissions = new ArrayList<String>();
		if (permissionList != null) {
			for (Permission vPermission : permissionList) {
				// 将数据库中的权限标签 符放入集合
				permissions.add(vPermission.getPermissionCode());
			}
		}

		// 查到权限数据，返回授权信息(要包括 上边的permissions)
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		// 将上边查询到授权信息填充到simpleAuthorizationInfo对象中
		simpleAuthorizationInfo.addStringPermissions(permissions);

		return simpleAuthorizationInfo;
	}

	// 清除缓存 在service中全下修改后调用
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}

}
